Ext.require([
    'Ext.form.field.ComboBox',
    'Ext.form.FieldSet',
    'Ext.tip.QuickTipManager',
    'Ext.toolbar.Paging',
    'Ext.grid.*',
    'Ext.data.*',
    'Ext.util.*',
    'Ext.state.*'
]);
Ext.onReady(function() {
	  var StoreList = [
	                         {"value":"1","text":"建筑面积"},
	                         {"value":"2","text":"套内面积"},
	                        /* {"value":"3","text":"套(别墅/排屋)"},*/
	                         {"value":"4","text":"个(车位)"}
	                         ];
	  
	  var schemeStore = Ext.data.Store({
	    	autoDestroy: true,
	        fields :["value","text"],
	        data : StoreList
	    });
	  
	  
	  
	  var typeList = [
                       {"value":"0","text":"按折后总价"},
                       {"value":"1","text":"按折扣比例"}
                       ];

var typeStore = Ext.data.Store({
  	autoDestroy: true,
      fields :["value","text"],
      data : typeList
  });
	  
	var fileAttachment = Ext.create('component.file.attachment',{
	    processInstanceId: '',
	    imageType: "6",
	    contextPath:contextPath
	});
	var form = new Ext.form.FormPanel({
		//title : "价格方案",
		region : 'north',
		minHeight : 220,
		frame : true,
		items:[
		       {
		    	   fieldLabel: "方案名称",
		    	   xtype:'textfield',
		    	   id:'name',
		    	   maxLength:50,
		    	   maxLengthText:'超过长度',
		    	   allowBlank:false,
			       blankText:'不能为空'
		       },{
		    	   fieldLabel:'折扣方式:',
		    	   xtype:'combobox',
		    	   displayField: "text",
		    	   valueField:"value",
		    	   store:typeStore,
		    	   id:'typeStore',
		    	   allowBlank:false,
			       blankText:'不能为空',
		    	   listeners:{
		    		   change:function(val){
		    			   if(val.value==0){
		    				   grid.columns[5].setText("折后总价（元）");
		    			   }else if(val.value==1){
		    				   grid.columns[5].setText("折扣比例（%）");
		    			   }
		    		   }
		    		   
		    	   }
		    	
		       }, {
		    	   xtype:"displayfield",					
		    	   fieldLabel:"方案房产",
		    	   id:"secheme",
		    	   value:manageObject
		    	  
		       },{
		    	   store:schemeStore,
		    	   id:'valuationType',
		    	   xtype:'combobox',
		    	   fieldLabel:'计价方式',
		    	   displayField: "text",
		    	   valueField:"value",
		    	   allowBlank:false,
			       blankText:'不能为空',
		    	   listeners:{
		    		   render:function(val){
			    		   if(val=="1"){
			    			   return "建筑面积";
			    		   }else if(val=="2"){
			    			   return "套内面积";
			    		   }else if(val=="3"){
			    			   return "套(别墅/排屋)";
			    		   }else if(val=="4"){
			    			   return "个/车位";
			    		   }
			    	   }
		    	   }
		    	 
		       },{
		    	   xtype:'datefield',
		    	   format:'Y-m-d',
		    	   fieldLabel:'方案执行日期',
		    	   id:'executionDate'
		       },{
		    	   xtype:'textarea',
		    	   fieldLabel:'方案说明',
		    	   width:500,
			       id:'remark'	   
		       },fileAttachment]
	});
	
 	Ext.QuickTips.init();
    var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
        clicksToEdit: 1
    });

    var noTradeHouse = "1";
    if(priceScheme != null && priceScheme != ""){
        noTradeHouse = "0";
	}

    var gridStore = Ext.create('Ext.data.Store', {
        fields: ["id","comboxText","buildingArea", "innerArea", "price","totalPrice","discountRate","floatingRange"],
        remoteSort: false,
        proxy: {
            type: 'ajax',
            url: jypath+'/marketing/priceScheme/findRoomList?treeId='+treeId+"&id="+bid+"&noTradeHouse="+noTradeHouse,
            reader: {   
                type: 'json', 
                root: 'rows',  
                totalProperty: 'total' 
            }
        },
        autoLoad: true  //即时加载数据
    });
    
	
	
    var grid = Ext.create('Ext.grid.Panel', {
        store: gridStore,
        //columnLines: true,
        region:'center',
        //minHeight : 250,
        columns: [{
        	  text: '房号',
              dataIndex: 'comboxText',
              width:'30%'
        },{   
        	text: '建筑面积', 
            dataIndex: 'buildingArea',
            width:'11%'
        },{
        	text: '套内面积', 
            dataIndex: 'innerArea',
            width:'11%'
        },{
        	text: '表单价', 
            dataIndex: 'price',
            editor: {
                xtype: 'numberfield',
                hideTrigger:true
            },
            width:'11%'
            
        },{
        	text: '表总价', 
            dataIndex: 'totalPrice',
            editor: {
                xtype: 'numberfield',
                hideTrigger:true
            },
            width:'11%'
        },{
        	text: '底价', 
            dataIndex: 'discountRate',
            editor: {
                xtype: 'numberfield',
                hideTrigger:true
            },
            width:'11%'
        },{
        	text: '浮动范围', 
            dataIndex: 'floatingRange',
            editor: {
                xtype: 'numberfield',
                hideTrigger:true
            },
            width:'15%'
        }],
        selModel: {
            selType: 'rowmodel'
        },
        viewConfig: {
            stripeRows: true
        },
        plugins: [cellEditing],
        listeners:{
        	'edit':function(editor, e){
        		//验证折扣方式对应金额
        		var record = e.record;
        		var editorField=editor.context.field;
        		if(editorField=="discountRate"){
        			var typeStore=Ext.getCmp("typeStore").getValue();
        			if(typeStore=="" || null==typeStore){
        			   Ext.Msg.alert("提示","请选择折扣方式");
     				   return;
        			}
        			
        			var discountRateValue=record.get("discountRate");
                    if(discountRateValue!="" && null!=discountRateValue){
                    	if(typeStore=="0"){
                			//折后总价
                			if(discountRateValue<0){
                			   Ext.Msg.alert("提示","请确认折后总价大于0");
            				   return;
                			}
                		}else if(typeStore=="1"){
                			//折扣比例
                			if(discountRateValue<0 || discountRateValue>100){
                				Ext.Msg.alert("提示","折扣比例范围为0 ~ 100%，请确认后填入");
                				return;
                			}
                		}
                    }
            		
        		}
        		if(editorField=="floatingRange"){
        			//var typeStore=Ext.getCmp("typeStore").getValue();
        			//if(typeStore=="0"){
        				var discountRateValue=record.get("floatingRange");
        				if(discountRateValue < 0 || discountRateValue > 10000){
        					var row = e.record;
        					Ext.Msg.alert("提示","浮动范围数值需在0~10000之间");
        					row.set("floatingRange",null);
        				}
        			//}
        		}
        		//验证折扣方式对应金额
        		
        		
        		var valuationType = Ext.getCmp("valuationType").getValue();
        		if(valuationType==null||valuationType==""){
        			//alert框,重新设定位置无效.代码先放着
        	/*		 Ext.Msg.alert({
        			 	title: "系统提示",
        			 	msg: "请选择计价方式!"
        			 }).setPosition(0,250,true).show();*/
        			Ext.Msg.alert("提示","请选择计价方式");
        		}else{
        			//当选择建筑面积计价时：建筑面积*单价=总价
        			var row = e.record;
        			if(valuationType=="1"){
        				var buildingArea = row.get("buildingArea");
        				var price = row.get("price");
        				
        				var totalPrice = parseFloat(buildingArea)*parseFloat(price);
        				if(editor.context.field=="price"){
        					if(null==price)return;
        					row.set("totalPrice",totalPrice.toFixed(2));
        				}else if(editor.context.field=="totalPrice"){
        					var priceCellValue =0;
        					if(parseFloat(buildingArea)>0){
        						priceCellValue = row.get('totalPrice')/buildingArea;
        					}
        					row.set("price",priceCellValue.toFixed(2));
        				}
        			}else if(valuationType=="2"){
        				//当选择套内面积计价时：套内面积*单价=总价
        				var innerArea = row.get("innerArea");
        				var price = row.get("price");
        				var totalPrice = parseFloat(innerArea)*parseFloat(price);
        				if(editor.context.field=="price"){
        					if(null==price)return;
        					row.set("totalPrice",totalPrice.toFixed(2));
        				}else if(editor.context.field=="totalPrice"){
        					var priceCellValue =0;
        					if(parseFloat(innerArea)>0){
        						priceCellValue = row.get('totalPrice')/innerArea;
        					}
        					row.set("price",priceCellValue.toFixed(2));
        				}
        				
        			}else if(valuationType=="3"){
        				//当选择套(别墅/排屋)时 : 先填总价，然后计算单价=总价/建筑面积
        				if(row.get("price")!=null){
        					row.set("price",null);
        				}
        				var totalPrice = row.get("totalPrice");
        				if(totalPrice==null){
        					row.set("price",null);
        				}else{
        					if(null==totalPrice)return;
        					var buildingArea = row.get("buildingArea");
        					if(parseFloat(buildingArea)<=0){
        						var price=0;
        						row.set("price",price.toFixed(2));
        					}else{
        						var price = parseFloat(totalPrice)/parseFloat(buildingArea);
        						row.set("price",price.toFixed(2));
        					}
            				
            				
        				}
        			}else if(valuationType=="4"){
        				if(row.get("price")!=null){
        					row.set("price",null);
        				}
        			}
        		}
        	}
        },
        dockedItems: [{
            xtype: 'toolbar',
            dock: 'bottom',
            ui: 'footer',
            layout: {
                pack: 'center'
            },
            items: [{
                minWidth: 80,
                text: '提交审核',
                id:'save_button',
                handler:PriceSchemeBatch
            },{
                minWidth: 80,
                text: '返回',
                id:'back_button',
                handler:backProjectDetail
            }]
        }
        ],tbar:[
            {
                xtype : "container",
                layout : "hbox",
                items : [ {
                    xtype : "checkboxgroup",
                    id : "ckRoomStatus",
                    name : "followModes",
                    hidden:true,
                    width : 90,
                    items : [ {
                        boxLabel : '未交易房源',
                        inputValue : '1',
                        listeners : {
                            'change' : function(el, value) {
                            	var newUrl = jypath+'/marketing/priceScheme/findRoomList?treeId='+treeId+"&id="+bid;
                            	if(value){
                                    newUrl += "&noTradeHouse=1";
								}
                                gridStore.getProxy().url = newUrl;
                                gridStore.load();
                            }
                        }
                    }]
                } ]

            },
			{
				text : '下载模板',
				icon : jypath + '/resources/ExtJSicons/page/page_excel.png',
				handler : downExcelModel
			},{
				text : '导入模板',
				icon : jypath + '/resources/ExtJSicons/page/page_white_excel.png',
				handler : importExcelModel
				
			}]
    });
	
	function downExcelModel(){
		//是否选择了计价方式
		var floorType=Ext.getCmp("typeStore").getValue();
		if(floorType==null||floorType==""){
			Ext.Msg.alert('提示', '请选择底价方式!');
			return;
		}
		//判断是否存在价格方案.
		//存在方案,显示全部,不存在只下载部分房源(除认筹、认购、签约房源)
        /*
        var rsChecked = Ext.getCmp("ckRoomStatus").getChecked();
		if(rsChecked && rsChecked.length > 0){
            noTradeHouse = rsChecked[0].inputValue;
		}
		*/
		location.href=jypath+"/excel/downloadExcelModel?treeId="+treeId+"&floorType="+floorType+"&noTradeHouse="+noTradeHouse;
	}
	
	
	function importExcelModel(){
		
		createImportWindow().show();
	}

	var modelForm = null;
	function createImportWindow(){
		modelForm = windowForm();
		return new Ext.create("Ext.window.Window",{
			 title: "上传文件",
			 id:'modelForm',
			 width: 350,
			 height:85,
			 plain: true,
		     modal: true,
		     x: 250,
		     y: 250,
		     items:[modelForm],
			 buttons: [
				{ xtype: "button", text: "确定", handler: importModel },
				{ xtype: "button", text: "取消", handler: function () { this.up("window").close(); } }
		   	]
		});
	}
	
	
	function importModel(){
		
		var form = modelForm.getForm();
		 form.submit({
			 url: jypath + '/excel/importModel',
             waitMsg: '正在导入...',
             success:function(form, action) {
            	var id = action.result.data;
            	var newUrl = jypath+"/excel/refreshGrid?no="+id;
         		gridStore.getProxy().url = newUrl;  
         		gridStore.load();
         		Ext.getCmp("modelForm").close();
             },
             failure: function(form, action){
             	Ext.Msg.alert("系统提醒",'导入异常!');
             }
		 });
	}
	
	function windowForm(){
		return Ext.create('Ext.form.Panel',{
			 items: [{
		            xtype: 'filefield',
		            emptyText: '选择文件',
		            fieldLabel: '模版文件',
		            name: 'file',
		            buttonText: '',
		            buttonConfig: {
		            	icon : jypath + '/resources/ExtJSicons/page/page_white_excel.png'
		            }
		        }]
		});
	}
	var form = new Ext.form.FormPanel({
		title:'价格方案',
		frame : true,
		items: [form,grid],
		renderTo:Ext.getBody()
   })
	
/*	var viewport = Ext.create('Ext.Viewport', {
		autoScroll:true,
		items : [form,grid]
	});*/
	
	function PriceSchemeBatch(){
		var jsonArray=[];
		var records=gridStore.getCount();
		var flag = true;
		if(records<=0){
			Ext.Msg.alert('提示', '没有房间或者车位,无法新增价格方案!');
			flag=false;
		}
		var typeStore=Ext.getCmp("typeStore").getValue();
		if(typeStore=="" || null==typeStore){
		   Ext.Msg.alert("提示","请选择折扣方式");
			   return;
		}
		var addCount=0;
		for(var i=0;i<records;i++){
			var record = gridStore.getAt(i).data;
			var discountRateValue=record.discountRate;
			//当表总价不为空，则认为当前数据有效，则需要检查数据的合理性
			var totalPrice=record.totalPrice;
			if(null!=totalPrice && totalPrice!="" ){
				if(typeStore=="0"){
					if(null==discountRateValue || discountRateValue==""){
						//折后总价
	            		Ext.Msg.alert("提示","第"+(i+1)+"行,折后总价必填");
	 				    return;
		            }else{
		            	//折后总价
						if(discountRateValue<0){
						   Ext.Msg.alert("提示","第"+(i+1)+"行,请确认折后总价大于0");
						   return;
						}
		            }
        			
        		}else if(typeStore=="1"){
        			if(null==discountRateValue || discountRateValue==""){
	        			//折扣比例
	        			Ext.Msg.alert("提示","第"+(i+1)+"行,折扣比例必填");
	 				    return;
        			}else{
        				//折扣比例
        				if(discountRateValue<0 || discountRateValue>100){
        					Ext.Msg.alert("提示","第"+(i+1)+"行,折扣比例范围为0 ~ 100%，请确认后填入");
        					return;
        				}
        			}
        		}
				addCount=addCount+1;
				jsonArray.push(Ext.JSON.encode(gridStore.getAt(i).data));
			}
			
		}
		if(addCount<=0){
			Ext.Msg.alert("提示","房间或车位缺少有效价格,无法新增价格方案!");
			return;
		}
		var resultJson=Ext.JSON.encode(jsonArray);
		
		//验证数据
	
		if(flag){
			if(form.getForm().isValid()){
				var fileUrlArr = fileAttachment.getFileArrs();
				Ext.getCmp("save_button").setVisible(false);
				Ext.Ajax.request({
					url: jypath+'/marketing/priceScheme/add',
					params:{
						floorType:Ext.getCmp("typeStore").getValue(),
						name:Ext.getCmp("name").getValue(),
						valuationType:Ext.getCmp("valuationType").getValue(),
						execution:dateFormat(Ext.getCmp("executionDate").getValue()),
						remark:Ext.getCmp("remark").getValue(),
						gridJson:resultJson,
						treeId:treeId,
						secheme:manageObject,
						fileUrlArr:fileUrlArr,
						imageType: "8",
						token:token
					},
					callback: function (options, success, response) {
						 if (success) {
							 var obj = JSON.parse(response.responseText);
							 if(obj.res=="1"){
								 fileAttachment.deleteBtnHidden();
								 Ext.MessageBox.alert("系统提示", "提交成功", function(but) {
									 parent.TabControlRemove(treeId);
									
								 });
							 }else{
								 Ext.MessageBox.alert("系统提示",obj.resMsg); 
								 token = obj.obj;
								 Ext.getCmp("save_button").setVisible(true);
							 }
			        	 }else{
			        		 Ext.MessageBox.alert("系统提示","系统异常!");
			        		 token = obj.obj;
			        		 Ext.getCmp("save_button").setVisible(true);
			        	 }
					}
				});
			}
		}
	}
	
	function dateFormat(value){ 
	    if(null != value){ 
	        return Ext.Date.format(new Date(value),'Y-m-d'); 
	    }else{ 
	        return null; 
	    } 
	} 
	if(priceScheme!=null&&priceScheme!=""){
		var obj = JSON.parse(priceScheme);
		if(obj.executionDate!=null){
			Ext.getCmp("executionDate").setValue(dateFormat(obj.executionDate.time));
		}
		
		//查看状态下
		Ext.getCmp("name").setValue(obj.name);
		Ext.getCmp("valuationType").setValue(obj.valuationType);
		Ext.getCmp("remark").setValue(obj.remark);
		Ext.getCmp("typeStore").setValue(obj.floorType);
		Ext.getCmp("save_button").setVisible(false);
	}

	function backProjectDetail(){
		 if(bid!=null&&bid!=""){
			 var tabKey = "sch_"+bid;
			 parent.TabControlRemove(tabKey);
		 }else if(treeId!=null&&treeId!=""){
			 parent.TabControlRemove(treeId);
		 }
	}
	
	if(processFlag!=null&&processFlag!=""){
		Ext.getCmp("back_button").setVisible(false);
	}

});